package cn.openea.perpartner.cms.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.cms.factory.UserContext;
import cn.openea.perpartner.common.auth.config.AuthConfig;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-07-21 14:26
 */
@Component
public class UserContextInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
                             final Object handler) throws Exception {
        LoginBody loginUser = (LoginBody) request.getAttribute(AuthConfig.SSO_USER);
        if (BeanUtil.isNotEmpty(loginUser)){
            UserContext.setLoginUser(loginUser);
        }else {
            UserContext.clear();
        }
        return true;
    }
    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
                           final Object handler, final ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(final HttpServletRequest request,
                                final HttpServletResponse response,
                                final Object handler, final Exception ex) throws Exception {
        UserContext.clear();
    }
}
